/**
 * Created by Scoot on 2017/2/17.
 */
var cartId = getCookie("mobile_cartId")||"",merchantInventoryId='',//网点id
    productAmount='',orderCode = getCookie("orderCode")||"";
var shippingFee='', orderAmount='';
var isTotal = true, memberAddressId = '';//收货地址id
var _remark = '';
var isWX = true;
var payTpye = "1";

var isApp = false;

var equipmentType = "common";
if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
    equipmentType= "ios";
} else if (/(Android)/i.test(navigator.userAgent)) {
    equipmentType = "android";
} else {
    equipmentType = "common";
}


$(function(){

    isWeiXin();

    post({
        url : "/isLogin",
        success : function(data){
            if(!data){
                go("/login/index.html");
            }
        }
    });

    if(isWX){
        post({ //判断当前订单的微信支付状态
            url:"/order/queryWechatStatus",
            data: {orderCodes:orderCode},
            success:function(data){
                if(data=="success"){
                    getOrderDetail();
                }else{
                    queryOrderStatus();
                }
            }
        })
    }else{
        queryOrderStatus();
    }

    //取消填写地址
    $(".adrees_cancel").on("click",function(){
        go("/cart/index.html");
    });
    //跳转到选择地址页面
    $(".adrees_affirm").on("click",function(){
        go("/member/addressmanagement/selectaddress.html");
    });

    $(".message_alert_affirm").on("click",function(){
        $(".message_alert").addClass("tab");
    });

    //头部返回按钮
    $(".header .left").click(function () {
        $(".back_cover,.back_alert").css("display","block");
    });
    //继续填单
    $(".back_alert .right").click(function () {
        $(".back_cover,.back_alert").css("display","none");
    });

    //选择支付方式
    $(".pay_list").click(function(){
        payTpye = $(this).data("type");
        $(".pay_list").removeClass("pay-selected");
        $(this).addClass("pay-selected");
    });

});

function queryOrderStatus(){

    var _data = {
        id:cartId,
        orderCode:orderCode
    };

    post({
        url:"/order/confirmInitial",
        data:_data,
        success:function(data){

            if(!data.memberAddressDTO){
                $(".no_adrees").removeClass("tab");
             }else{
                $(".no_adrees").addClass("tab");
             }

            $(".add_cart .btn").removeAttr("disabled");
            productAmount=data.productAmount;
            shippingFee=data.shippingFee;
            orderAmount=data.orderAmount;

            dealData(data);
            address(data.memberAddressDTO);

            var list = data.cartListDTO;
            if(list[0]["merchantInventoryId"]){
                merchantInventoryId = [];
                _ids = [];
                for(var i=0;i<list.length;i++){
                    _ids.push(list[i]["id"]);
                    merchantInventoryId.push(list[i]["merchantInventoryId"]);
                }
                merchantInventoryId = merchantInventoryId.toString();
            }
        }
    });

    post({ //判断订单状态
        url:"/order/queryOrderStatus",
        data:{orderCodes:orderCode},
        success:function(data){
            if(data == "success"){
                $(".add_cart .btn").click(function(){
                    $(this).attr("disabled","disabled");
                    setCookie("pay-content","store"); //为了标记这是 普通商品下单，用于app支付失败后返回支付失败页面
                    if(memberAddressId != ''){
                        if(equipmentType == "ios"){
                            try{
                                //ifApp();
                                window.webkit.messageHandlers.ifApp.postMessage('');
                                isApp = true;
                            }catch (e){
                                isApp = false;
                            }
                        }else if(equipmentType == "android"){
                            try{
                                isApp = contact.ifApp();
                            }catch (e){
                                isApp = false;
                            }
                        }else{
                            isApp = false;
                        }
                        goPay();
                    }else{
                        $(".address_alert").css("display","block");
                        setTimeout(function(){
                            $(".address_alert").css("display","none");
                        },3000)
                    }
                });
                $(".gat_alert_affirm").click(function(){
                    $(".gat_background").addClass("tab");
                });
            }else{
                $(".gat_background .gat_alert p").text("对不起，无法购买，存在此订单，请在订单列表中查看订单详细信息!");
                $(".gat_background").removeClass("tab");
                $(".gat_alert_affirm").click(function(){
                    go("/member/myorders/allorder.html");
                });
            }
        }
    });
}

//微信支付，第二次进此页面，获取订单信息，然后调起微信支付
function getOrderDetail(){
    var _data = {
        id:cartId,
        orderCode:orderCode
    };

    post({
        url:"/order/confirmInitial",
        data:_data,
        success:function(data){

            if(!data.memberAddressDTO){
                $(".no_adrees").removeClass("tab");
             }else{
                $(".no_adrees").addClass("tab");
             }
            productAmount=data.productAmount;
            shippingFee=data.shippingFee;
            orderAmount=data.orderAmount;
            dealData(data);
            address(data.memberAddressDTO);
            var list = data.cartListDTO;
            if(list[0]["merchantInventoryId"]){
                merchantInventoryId = [];
                _ids = [];
                for(var i=0;i<list.length;i++){
                    _ids.push(list[i]["id"]);
                    merchantInventoryId.push(list[i]["merchantInventoryId"]);
                }
                merchantInventoryId = merchantInventoryId.toString();
            }
            weiXinPay();
        }
    });
}

//去支付
function goPay(){

    if(isTotal){
        post({
            url: "/order/queryOrderStatus",
            data: {orderCodes:orderCode},
            success: function (data) {
                if (data == "success") {
                    _remark = $(".remark_input").val();
                    if(isWX && isApp == false && payTpye == "1"){  //微信支付
                        go("/order/saveWeChat?cartId="+cartId+"&merchantInventoryId="+merchantInventoryId+"&orderCodes="+orderCode+"&shippingFee="+shippingFee+"&memberAddressId="+memberAddressId+"&remark="+_remark);
                    }else{
                        if(isApp == true && payTpye == '1'){//如果是在app并且是微信支付
                            appPay();
                        }else if(isApp == false && payTpye == '1'){
                            $(".add_cart .btn").removeAttr("disabled");
                            $(".message_alert").removeClass("tab");
                        }else{ //支付宝支付
                            alipay();
                        }
                    }
                } else {
                    $(".gat_background .gat_alert p").text("对不起，无法购买，存在此订单，请在订单列表中查看订单详细信息!");
                    $(".gat_background").removeClass("tab");
                    $(".gat_alert_affirm").click(function () {
                        go("/member/myorders/allorder.html");
                    });
                }
            }
        });
    }else{   //库存不足
        $(".gat_background .gat_alert p").text("库存不足！");
        $(".gat_background").removeClass("tab");
    }
}

function appPay(){

    var _data = {
        cartId:cartId,
        merchantInventoryId:merchantInventoryId,
        orderCodes:orderCode,
        shippingFee:shippingFee,
        memberAddressId:memberAddressId,
        remark:_remark
    };
    post({
        url:'/order/saveWeChatAPP',
        data:_data,
        success:function(data){
            //console.log(data);
            var p = data.split(',');
            if(equipmentType == "ios"){
                //wxpay(p[0],p[1],p[2],p[3],p[4],p[5]);
                var message = {
                    'partnerid' : p[0],
                    'prepayid' : p[1],
                    'packages' : p[2],
                    'noncestr' : p[3],
                    'timestamp' : p[4],
                    'sign' : p[5]
                };
                calliOSwxpay(message);
                //window.webkit.messageHandlers.wxpay.postMessage(message);
            }else{
                contact.wxpay(p[0],p[1],p[2],p[3],p[4],p[5]);
            }

        }
    })
}

/*function ifApp() {
    window.webkit.messageHandlers.ifApp.postMessage();
}*/

function calliOSwxpay(message) {
    /*var message = {
        'partnerid' : 'url',
        'prepayid' : 'itle',
        'packages' : 'Imageurl',
        'noncestr' : 'text',
        'timestamp' : 'Imageurl',
        'sign' : 'text',
    };*/
    window.webkit.messageHandlers.wxpay.postMessage(message);
}

function alipay(){

    post({
        url:"/order/save",
        data:{
            cartId:cartId,
            merchantInventoryId:merchantInventoryId,
            orderCodes:orderCode,
            shippingFee:shippingFee,
            memberAddressId:memberAddressId,
            remark:_remark
        },
        success:function(data){
            if(isWX){
                go("pay_tip.html?url="+encodeURIComponent("/alipay/payFor?code=" + data));
            }else{
                go("/alipay/payFor?code=" + data);
            }
        },
        requestError:function(msg){
            console.log(msg)
        }
    })
}

function weiXinPay(){
    var _appId = '';
    var _timeStamp= '';
    var _nonceStr = '';
    var _paySign = '';
    var _signType = '';
    var prepay_id = '';

    post({
        url:"/weChat/getWeChatDto",
        data:{cartId:cartId},
        success: function (data) {
            _appId = data.appId;
            _timeStamp = data.timeStamp;
            _nonceStr = data.nonceStr;
            _paySign = data.paySign;
            _signType = data.signType;
            prepay_id = data.prepay_id;
            if (typeof WeixinJSBridge == "undefined"){
                if( document.addEventListener ){
                    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                }else if (document.attachEvent){
                    document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                }
            }else{
                onBridgeReady();
            }
        }
    });

    function onBridgeReady(){
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest', {
                "appId":_appId,     //公众号名称，由商户传入
                "timeStamp":_timeStamp,         //时间戳，自1970年以来的秒数
                "nonceStr":_nonceStr, //随机串
                "package":prepay_id,
                "signType":_signType,         //微信签名方式：
                "paySign":_paySign //微信签名
            },
            function(res){
                if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                    go("/member/myorders/allorder.html");
                }else{
                    go("/member/myorders/obligation.html");
                }     // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
            }
        );
    }
}

//收货地址
function address(ads){

    if(!!ads){
        memberAddressId = ads.id;
        $(".address").css("display","none");
        $(".address_selected").css("display","block");
        $(".address_selected .name").html(ads.consignee+"<span>"+ads.mobile+"</span>");
        $(".address_selected .more_single").html(ads.addressDetail);

    }else{
        //merchantInventory();
        $(".address").css("display","block");
        $(".address_selected").css("display","none");
    }
}

//网点地址
function merchantInventory(){
    post({
        url:"/order/findMerchantInventory",
        data:{
            cartId:cartId,
            orderCodes:orderCode,
            memberAddressId:memberAddressId
        },
        success:function(data){
            console.log(data)
            cartId=[];
            merchantInventoryId = [];
            for(var i=0;i<data.length;i++){
                cartId.push(data[i].id);
                merchantInventoryId.push(data[i].merchantInventoryId);
            }
            cartId = cartId.toString();
            merchantInventoryId = merchantInventoryId.toString();
        }
    })
}

function dealData(data){

    var list = data.cartListDTO;
    var _html = '';
    for(var i=0;i<list.length;i++){
        _html += '<div class="list"><div class="list_detail">';
        _html += '<div class="img left"><img src="'+SERVER_CONTEXT_PATH+'/load/picture/'+list[i]["imageUrl"]+'"></div>';
        _html += '<div class="info left"><p class="more_single">'+list[i]["productName"]+'</p>';
        _html += '<p class="price more_single">￥'+(list[i]["price"]).toFixed(2)+'<span class="right">X&nbsp;'+list[i]["num"]+'</span></p>';
        _html += '<p class="more_single">';

        for(var j=0;j<list[i]["specifications"].length;j++){
            _html += list[i]["specifications"][j]["specName"]+'：'+list[i]["specifications"][j]["specValue"] + "&nbsp;";
        }
        _html += '</p></div></div>';

        if(!!data.memberAddressDTO){
            if(list[i]["num"]>list[i]["total"]){
                _html += '<p class="understock">库存不足</p>';
                isTotal = false;
            }
        }
        _html += '</div>';
    }
    $(".main").html(_html);

    $(".icon_cart p span").text("￥"+(data.orderAmount).toFixed(2));
    $(".order_detail .productAmount").text("￥"+(data.productAmount).toFixed(2));
    $(".order_detail .shippingFee").text("￥"+(data.shippingFee).toFixed(2));
    $(".order_detail .orderAmount").text("￥"+(data.orderAmount).toFixed(2));
}

invoice();//发票显示
function invoice(){

    var flag = false;
    $(".invoice").click(function(){
        flag = !flag;
        if(flag){
            $(".invoice .right").css("display","none");
            $(".invoice-img").css("display","block");
        }else{
            $(".invoice .right").css("display","block");
            $(".invoice-img").css("display","none");
        }
    });
    $(".invoice-img").click(function(){
        $(".invoice .right").css("display","block");
        $(".invoice-img").css("display","none");
        flag = !flag;
    });

}

//判断是否是微信
function isWeiXin(){
    var ua = window.navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i) == 'micromessenger'){
        isWX = true;
        $(".invoice-img").html('<img src="img/2DHorse.png">');
        $(".payment .pay_list").css("display","block");
        return true;
    }else{
        isWX = false;
        $(".payment .pay_list").css("display","block");
        $(".invoice-img").html('<p>发票请到公众号上申请，步骤：微信中搜索"火匣"并关注火匣微信公众号。</p>');
        return false;
    }
}

function iosApp(str){
    isApp = true;
    return true;
}

$(".pay_botton .cancel").click(function(){
    $(".container").css("display","block");
    $(".pay_container").css("display","none");
});
